﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace AuctionHouseClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
       
        private const int PORT = 12345;

        private NetworkStream networkstream;
        private BinaryReader Binreader;
        private BinaryWriter Binwriter;
        private Socket server;
        private IPEndPoint serveradr;
        private ClientThreads clientThreads;
        private Thread modtagKlientTraade;

        private delegate void clientReceivedDelegate(string klient);
        
        public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }
        public MainWindow()
        {
            InitializeComponent();
        
            Title = "IP: " + LocalIPAddress()+" - "+Environment.UserName;

            this.serveradr = new IPEndPoint(IPAddress.Parse("127.0.0.1"), PORT);

            this.clientThreads = new ClientThreads();


            this.clientThreads.ClientReceivedEvent += new ReceiveClient(this.ClientReceivedHandler);

            // Tilstandsstyring af GUI
            txtKlientInput.IsEnabled = false;
            txtKlientInput.Text = "";
            btnLogon.IsEnabled = true;
            btnLogoff.IsEnabled = false;
            btnSendKlient.IsEnabled = false;
            btnLogon.Focus();
 
        }

        // Event Handler
        public void ClientReceivedHandler(string client)
        {
            txtKlientOutput.Dispatcher.BeginInvoke(new clientReceivedDelegate(this.clientReceivedHandlerInvoke), client);
        }

        private void clientReceivedHandlerInvoke(string client)
        {
            txtKlientOutput.Text += client + "\r\n";	// Skriv til Klient-output-område
        }

        private void btnSendKlient_Click(object sender, RoutedEventArgs e)
        {
            this.Binwriter.Write(txtKlientInput.Text);
            this.Binwriter.Flush();

            txtKlientInput.Text = "";
        }

        private void btnLogon_Click(object sender, RoutedEventArgs e)
        {
            this.server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
               string navn;
            navn = tbLoginName.Text;
            if (navn !="")
            {
            try{
            this.server.Connect(this.serveradr);
            Console.WriteLine(navn + " forbandt til server...");
            }
            catch (SocketException ex)
            {
                Console.WriteLine(navn + " kan ikke forbinde til server...");
                txtKlientOutput.Text += navn + " kan ikke forbinde til server...\n";
                Console.WriteLine(ex.ToString());
                return;
            }
            NetworkStream networkStream;
                BinaryReader reader;
                BinaryWriter writer;

                networkStream = new NetworkStream(this.server);
                reader = new BinaryReader(networkStream);
                writer = new BinaryWriter(networkStream);

                // Start modtag-Klient-tråd
                this.modtagKlientTraade = new Thread(new ParameterizedThreadStart(clientThreads.ReceivedClientInput));
                this.modtagKlientTraade.Start(reader);

                // Tilstandsstyring af GUI
                txtKlientOutput.Text = "";
                txtKlientInput.IsEnabled = true;
                btnLogon.IsEnabled = false;
                btnLogoff.IsEnabled = true;
                btnSendKlient.IsEnabled = true;
            }
            else
            {
                MessageBox.Show("Venligst angiv et navn");
            }
           
        }

        private void btnLogoff_Click(object sender, RoutedEventArgs e)
        {
            // Luk forbindelse til server
            this.Binreader.Close();
            this.Binwriter.Close();
            this.networkstream.Close();
            this.server.Shutdown(SocketShutdown.Both);
            this.server.Close();

            this.modtagKlientTraade.Join();    // vent på at tråd afsluttes
            txtKlientOutput.Text += "\r\nLukker forbindelsen til server...";

            // Tilstandsstyring af GUI
            txtKlientInput.IsEnabled = false;
            txtKlientInput.Text = "";
            btnLogon.IsEnabled = true;
            btnLogoff.IsEnabled = false;
            btnSendKlient.IsEnabled = false;
            btnLogon.Focus();
        }
    }
}
